/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable, runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions_transfer';
import ABRouteTable from './ABRouteTable';
import ABRouteSetting from './ABRouteSetting';

const FromItem = Form.Item;

const PriceTransferForm = ({ priceId, modal, onSubmit, onCancel }) => {
  const { ccPriceTransferStore: store } = useStore();
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [price] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [showSetting, setShowSetting] = useState(false);

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
  };

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (priceId) {
        const data = await store.get(priceId);
        await store.dockingStationCity(data);
        editCtx.origin = _.cloneDeep(data);
        _.set(data, 'startMinorAreasGroup', { label: data.fromGroupNames, value: data.fromGroupNames });
        _.set(data, 'endMinorAreasGroup', { label: data.toGroupNames, value: data.toGroupNames });
        runInAction(() => _.assign(price, data));
      } else {
        // 添加操作,设置默认值
        runInAction(() => _.assign(price, { fromRoutes: [], toRoutes: [] })); // 处理为可观察
      }
    })();
  }, []);

  if (!price) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(price, name, value);
    // 联动效果可以在这里通过设置price属性实现
    if (name === 'priceConfig.specificSingleFare.RMB') {
      const prefix = _.trimEnd(name, '.RMB');
      _.set(price, `${prefix}.HKD`, parseFloat(value));
      _.set(price, `${prefix}.MOP`, parseFloat(value));
    }
    if (name === 'startMinorAreasGroup') {
      _.set(price, 'startMinorAreas', value.items.map((itm) => itm.itemId));
    }
    if (name === 'endMinorAreasGroup') {
      _.set(price, 'endMinorAreas', value.items.map((itm) => itm.itemId));
    }
    // if (name === 'dockingStation') {
    //   (async () => {
    //     const city = await store.apiDict.getDictItem('region', value);
    //     _.set(price, 'dockingStationCity', city?.name);
    //   })();
    // }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(price));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: PriceTransferForm.jsx:88 _ errors:', errors);
      return;
    }
    onSubmit?.(price);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={price}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['startMainArea', 'startMinorAreasGroup', 'endMainArea', 'endMinorAreasGroup', 'dockingStation', 'dockingStationCity', 'priceConfig.specificSingleFare.RMB']}
      />
      <TitleGrid colSpan={4} title={<span>{t`分段线路`}<Button type="primary" style={{ marginLeft: 24 }} onClick={() => { setShowSetting(true); }} >{t`选择分段线路`}</Button></span>} />
      {price.fromRoutes?.length > 0 && <ABRouteTable priceTransfer={price} />}

      <TitleGrid title={t`其他`} />
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['remark']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <Drawer
        visible={showSetting}
        title={t`选择多段线路`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setShowSetting(false)}
        width="90%"
      >
        <ABRouteSetting
          priceTransfer={price}
          onSubmit={(selection) => {
            setShowSetting(false);
            _.assign(price, selection);
          }}
        />
      </Drawer>
    </Form>
  );
};

export default observer(PriceTransferForm);
